<?php
/**
 * @Author: Xu Liu email:2867557054@qq.com
 * @Date:   2016-12-15 13:31:33
 * @Last Modified by:   Xu Liu
 * @Last Modified time: 2018-05-15 10:28:11
 */
if (!defined('IN_DISCUZ')) {
    exit('Access Denied');
}
class AuthorContrl
{
    public function __construct()
    {
        global $_G;
        !allowpostbook() && showmessage(lang('plugin/jameson_read', 'wuquanfabu'));
        $_G['jameson_read']['booksnum']    = C::t('#jameson_read#jamesonread_books')->count_by_uid($_G['uid']);
        $_G['jameson_read']['topbooksnum'] = C::t('#jameson_read#jamesonread_books')->counttop_by_uid($_G['uid']);
        $_G['jameson_read']['piaos']       = C::t('#jameson_read#jamesonread_authors')->fetch($_G['uid']);
    }
    public function index()
    {
        global $_G;
        $navtitle = lang('plugin/jameson_read', 'zuozhezhongxin');
        require_once './source/plugin/jameson_read/class/Page.class.php';
        if (!DB::result_first('SELECT count(*) FROM %t WHERE author_id=%d', array('jamesonread_authors', $_G['uid']))) {
            $authorinfo = array(
                'author_id'   => $_G['uid'],
                'groupid'   => $_G['groupid'],
                'status'      => 1,
                'edit'        => 1,
                'allowedit'   => 1,
                'yuepiao'     => 0,
                'tuijianpiao' => 0,
                'cuigengpiao' => 0,
                'zgsj'        => 0,
                'qzsj'        => 0,
                'setsj'       => 'zgsj',
            );
            C::t('#jameson_read#jamesonread_authors')->insert($authorinfo);
        } else {
            $authorinfo = C::t('#jameson_read#jamesonread_authors')->fetch($_G['uid']);
        }
        if ($keybookname = trim($_GET['book_name'])) {
            if (xfxs_isutf($keybookname) && (strtolower(CHARSET) != 'utf-8')) {
                $keybookname = diconv($keybookname, 'utf-8', CHARSET);
            } else if (!xfxs_isutf($keybookname) && (strtolower(CHARSET) == 'utf-8')) {
                $keybookname = diconv($keybookname, 'GB2312', 'utf-8');
            }
            $keybookcounts = C::t('#jameson_read#jamesonread_books')->count_search_at_author($_G['uid'], $keybookname);
            $page          = new Page($keybookcounts, 20, './plugin.php?id=jameson_read&contrl=author&act=index&book_name=' . $keybookname);
            $books         = C::t('#jameson_read#jamesonread_books')->fetch_search_at_author($_G['uid'], $keybookname, $page->getStart(), $page->getSize());
            $pageshow      = $page->show();
        } else {
            $page  = new Page(C::t('#jameson_read#jamesonread_books')->count_by_uid($_G['uid'], 1, $_G['uid']), 20, './plugin.php?id=jameson_read&contrl=author&act=index');
            $books = C::t('#jameson_read#jamesonread_books')->fetch_by_uid($_G['uid'], $page->getStart(), $page->getSize(), 1, $_G['uid']);
            if (count($books) < 20) {
                $allcate       = C::t('#jameson_read#jamesonread_categorys')->fetch_categoryid();
                $nofenleibooks = DB::fetch_all('SELECT * FROM %t WHERE  ' . DB::field('category_id', $allcate, 'notin').'  AND '.DB::field('uid',$_G['uid']) , array('jamesonread_books'));
                $books         = array_merge($books, $nofenleibooks);
            }
            $pageshow = $page->show();
        }
        $sales         = C::t('#jameson_read#jamesonread_buybooks')->fetch_sale_byuid($_G['uid']) + C::t('#jameson_read#jamesonread_buytids')->fetch_sale_byuid($_G['uid']);
        $dashangshouru = C::t('#jameson_read#jamesonread_dashang')->allprice($_G['uid']);
        include template("diy:author_index",0,'./source/plugin/jameson_read/template/');
    }
    public function book()
    {
        global $_G;
        $books      = array();
        $authorinfo = C::t('#jameson_read#jamesonread_authors')->fetch($_G['uid']);
        if ($book_id = intval($_GET['book_id'])) {
            // 是否被禁止编辑和删除图书
            $action = 'edit';
            $books  = C::t('#jameson_read#jamesonread_books')->fetchAllInfoById($book_id);
            !in_array($_G['uid'], array(1, $books['uid'])) && showmessage(lang('plugin/jameson_read', 'wuquanbianjibenshu'), dreferer());
            if ($_G['uid'] != 1 && ($_G['uid'] != $books['uid'])) {
                showmessage(lang('plugin/jameson_read', 'buyunxubianjitaren'), '');
            }
            $navtitle           = $books['book_name'] . '[' . lang('plugin/jameson_read', 'bianji') . ']-' . lang('plugin/jameson_read', 'zuozhezhongxin') . '-' . $_G['jameson_read']['jamesonread_title'];
            $books['categorys'] = C::t('#jameson_read#jamesonread_categorys')->fetch_all_parent(0);
            $books['childcate'] = C::t('#jamesonread_read#jamesonread_categorys')->fetch_all_parent($books['parent_id']);
            // 如果当前是pdf文件
            if ($books['is_pdf']) {
                $pdfs = array();
                $pdfs = C::t('#jameson_read#jamesonread_pdf')->fetch_by_bid($book_id);
            }
            // 书评
            require_once './source/plugin/jameson_read/class/Page.class.php';
            $books['dianpingcount'] = C::t('#jameson_read#jamesonread_dianping')->count_by_bid($book_id);
            if ($books['dianpingcount']) {
                $page              = new Page($books['dianpingcount'], 50, './plugin.php?id=jameson_read&contrl=author&act=book&forward=book_shuping&book_id=' . $book_id);
                $books['dianping'] = C::t('#jameson_read#jamesonread_dianping')->fetch_by_new($book_id, $page->getStart(), $page->getSize());
                $pageshow          = $page->show();
            }
            
            if (!$books['is_pdf']) {
                $books['sellcounts'] = C::t('#jameson_read#jamesonread_buytids')->count_by_bookid($book_id);
                $pagedy              = new Page($books['sellcounts'], 50, './plugin.php?id=jameson_read&contrl=author&act=book&forward=book_sell&book_id=' . $book_id);
                $books['dyjilus']     = C::t('#jameson_read#jamesonread_buytids')->fetch_by_bookid($book_id, $pagedy->getStart(), $pagedy->getSize());
            } else if ($books['is_pdf']) {
                $books['sellcounts']  = C::t('#jameson_read#jamesonread_buybooks')->count_by_bookid($book_id);
                $pagedy              = new Page($books['sellcounts'], 50, './plugin.php?id=jameson_read&contrl=author&act=book&forward=book_sell&book_id=' . $book_id);
                $books['dyjilus'] = C::t('#jameson_read#jamesonread_buybooks')->fetch_jilu_by_bookid($book_id,$pagedy->getStart(), $pagedy->getSize());
            }
            $leiji = C::t('#jameson_read#jamesonread_yongjin')->count_e_bybook($book_id,1);
            $pageshowdy          = $pagedy->show();
        } else {
            if ($authorinfo['status'] < 1) {
                showmessage(lang('plugin/jameson_read', 'wuquanfabu'), dreferer());
            }
            if (!$_G['jameson_read']['fid']) {
                showmessage(lang('plugin/jameson_read', 'weishezhitushubankuai'), dreferer());
            }
            $book_id            = 0;
            $navtitle           = lang('plugin/jameson_read', 'tianjiaxinshu') . '-' . lang('plugin/jameson_read', 'zuozhezhongxin');
            $books['categorys'] = C::t('#jameson_read#jamesonread_categorys')->fetch_all_parent(0);
            $tmp = current($books['categorys']);
            $books['parent_id'] = $tmp['category_id']; 
            $books['childcate'] = C::t('#jamesonread_read#jamesonread_categorys')->fetch_all_parent($books['parent_id']);
            $action             = 'add';
        }
        $sales         = C::t('#jameson_read#jamesonread_buybooks')->fetch_sale_byuid($_G['uid']) + C::t('#jameson_read#jamesonread_buytids')->fetch_sale_byuid($_G['uid']);
        $dashangshouru = C::t('#jameson_read#jamesonread_dashang')->allprice($_G['uid']);
        include_once './source/function/function_discuzcode.php';
        if ($_G['jameson_read']['authorcentergg']) {
            $authorcentergg = discuzcode($_G['jameson_read']['authorcentergg'], 0, 0);
        }
        // 版块信息
        $allowfid  = array();
        $forumlist = C::t('forum_forum')->fetch_all_fids(0, 'forum');
        foreach ($forumlist as $key => $value) {
            $tmp = unserialize(DB::result_first('SELECT threadplugin FROM %t WHERE fid=%d ', array('forum_forumfield', $value['fid'])));
            if (in_array('jameson_read', $tmp)) {
                $allowfid[] = $value;
            }
        }
        if($_G['jameson_read']['qiniuak'] && $_G['jameson_read']['qiniusk'] && $_G['jameson_read']['qiniuyuming'] && $_G['jameson_read']['qiniukongjian']){
            require_once  './source/plugin/jameson_read/class/autoload.php';
            $auth = new Auth($_G['jameson_read']['qiniuak'], $_G['jameson_read']['qiniusk']);
            $upToken = $auth->uploadToken($_G['jameson_read']['qiniukongjian']);
        }
        include template("diy:author_book",0,'./source/plugin/jameson_read/template/');
    }
    public function xiajia()
    {
        global $_G;
        $navtitle = lang('plugin/jameson_read', 'xiajiatushu') . '-' . lang('plugin/jameson_read', 'zuozhezhongxin');
        require_once './source/plugin/jameson_read/class/Page.class.php';
        $counts = C::t('#jameson_read#jamesonread_books')->count_by_uid($_G['uid'], 0);
        if ($counts) {
            $books = C::t('#jameson_read#jamesonread_books')->fetch_by_uid($_G['uid'], 0, $counts, 0);
        } else {
            $books = array();
        }
        $sales = C::t('#jameson_read#jamesonread_buybooks')->fetch_sale_byuid($_G['uid']) + C::t('#jameson_read#jamesonread_buytids')->fetch_sale_byuid($_G['uid']);
        include_once './source/function/function_discuzcode.php';
        if ($_G['jameson_read']['authorcentergg']) {
            $authorcentergg = discuzcode($_G['jameson_read']['authorcentergg'], 0, 0);
        }
        $dashangshouru = C::t('#jameson_read#jamesonread_dashang')->allprice($_G['uid']);
        include template("diy:author_xiajia",0,'./source/plugin/jameson_read/template/');
    }
    public function sell()
    {
        global $_G;
        $navtitle = lang('plugin/jameson_read', 'xiaoshou') . '-' . lang('plugin/jameson_read', 'zuozhezhongxin');
        require_once './source/plugin/jameson_read/class/Page.class.php';
        $counts = C::t('#jameson_read#jamesonread_buytids')->count_by_authorid($_G['uid']);
        if ($counts) {
            $page     = new Page($counts, 30, './plugin.php?id=jameson_read&contrl=author&act=sell');
            $tids     = C::t('#jameson_read#jamesonread_buytids')->fetch_by_authorid_page($_G['uid'], $page->getStart(), $page->getSize());
            $pageshow = $page->show();
        } else {
            $tids = array();
        }
        $currentp = $_GET['p'] ? intval($_GET['p']) : 1;
        if ((count($tids) < 30) || ($currentp == ceil($counts/30))) {
            $books = C::t('#jameson_read#jamesonread_buybooks')->fetch_books_by_authorid($_G['uid']);
        }
        // 通过佣金表查询
        $leiji = C::t('#jameson_read#jamesonread_yongjin')->count_e_byauthorid($_G['uid'],1);
        if ($_G['jameson_read']['authorcentergg']) {
            include_once './source/function/function_discuzcode.php';
            $authorcentergg = discuzcode($_G['jameson_read']['authorcentergg'], 0, 0);
        }
        include template("diy:author_sell",0,'./source/plugin/jameson_read/template/');
    }
    public function tongji()
    {
        global $_G;
        $navtitle = lang('plugin/jameson_read', 'tongji') . '-' . lang('plugin/jameson_read', 'zuozhezhongxin');
        $sales    = C::t('#jameson_read#jamesonread_buybooks')->fetch_sale_byuid($_G['uid']) + C::t('#jameson_read#jamesonread_buytids')->fetch_sale_byuid($_G['uid']);
        include_once './source/function/function_discuzcode.php';
        if ($_G['jameson_read']['authorcentergg']) {
            $authorcentergg = discuzcode($_G['jameson_read']['authorcentergg'], 0, 0);
        }
        $dashangshouru = C::t('#jameson_read#jamesonread_dashang')->allprice($_G['uid']);
        include template("diy:author_tongji",0,'./source/plugin/jameson_read/template/');
    }
    public function dashang()
    {
        global $_G;
        $counts        = C::t('#jameson_read#jamesonread_dashang')->count_by_authorid($_G['uid']);
        // 通过佣金表查询
        $leiji = C::t('#jameson_read#jamesonread_yongjin')->count_e_byauthorid($_G['uid'],2);
        if ($counts) {
            require_once './source/plugin/jameson_read/class/Page.class.php';
            $page        = new Page($counts, 50, './plugin.php?id=jameson_read&contrl=author&act=dashang');
            $pageshow    = $page->show();
            $dashangjilu = C::t('#jameson_read#jamesonread_dashang')->fetch_by_authorid($_G['uid'], $page->getStart(), $page->getSize());
        } else {
            $dashangjilu = array();
        }
        include_once './source/function/function_discuzcode.php';
        if ($_G['jameson_read']['authorcentergg']) {
            $authorcentergg = discuzcode($_G['jameson_read']['authorcentergg'], 0, 0);
        }
        $navtitle = lang('plugin/jameson_read', 'dashangjilu') . '-' . lang('plugin/jameson_read', 'zuozhezhongxin');
        include template("diy:author_dashang",0,'./source/plugin/jameson_read/template/');
    }
    public function shupiao()
    {
        global $_G;
        $shupiaos   = C::t('#jameson_read#jamesonread_authors')->fetch($_G['uid']);
        $piaojus    = DB::fetch_all('SELECT * FROM %t WHERE ' . DB::field('type', array(101, 102, 103), 'in'), array('jamesonread_topics'), 'type');
        $piaojunums = 0;
        foreach ($piaojus as $key => $value) {
            $piaojus[$key]['ing'] = (int) DB::result_first('SELECT count(*) FROM %t WHERE adv=%d AND url=%d AND type=%d', array('jamesonread_topics', $value['type'], $_G['uid'], 201));
            if ($value['type'] == 101) {
                // 月票
                $piaojus[$key]['num'] = $shupiaos['yuepiao'];
                $piaojunums += $shupiaos['yuepiao'];
                $piaojus[$key]['duihuan'] = intval($value['adv']) * intval($shupiaos['yuepiao']);
                $piaojus[$key]['field']   = 'yuepiao';
            } else if ($value['type'] == 102) {
                // 推荐票
                $piaojus[$key]['num'] = $shupiaos['tuijianpiao'];
                $piaojunums += $shupiaos['tuijianpiao'];
                $piaojus[$key]['duihuan'] = intval($value['adv']) * intval($shupiaos['tuijianpiao']);
                $piaojus[$key]['field']   = 'tuijianpiao';
            } else if ($value['type'] == 103) {
                // 催更票
                $piaojus[$key]['num'] = $shupiaos['cuigengpiao'];
                $piaojunums += $shupiaos['cuigengpiao'];
                $piaojus[$key]['duihuan'] = intval($value['adv']) * intval($shupiaos['cuigengpiao']);
                $piaojus[$key]['field']   = 'cuigengpiao';
            }
        }
        require_once './source/plugin/jameson_read/class/Page.class.php';
        $page       = new Page(DB::result_first('SELECT count(id) FROM %t WHERE uid=%d AND type=%d', array('jamesonread_piao', $_G['uid'], 2)), 30, './pllugin.php?id=jameson_read&contrl=author&act=shupiao&type=tixianjilu');
        $tixianjilu = C::t('#jameson_read#jamesonread_piao')->fetch_by_uid($_G['uid'], 2, $page->getStart(), 30);
        $pageshow   = $page->show();
        include_once './source/function/function_discuzcode.php';
        if ($_G['jameson_read']['authorcentergg']) {
            $authorcentergg = discuzcode($_G['jameson_read']['authorcentergg'], 0, 0);
        }
        $navtitle = lang('plugin/jameson_read', 'dashangjilu') . '-' . lang('plugin/jameson_read', 'zuozhezhongxin');
        include template("diy:author_shupiao",0,'./source/plugin/jameson_read/template/');
    }
    public function duihuan()
    {
        global $_G;
        if (FORMHASH != $_GET['formhash']) {
            showmessage(lang('plugin/jameson_read', 'laiyuanfeifa'));
        } else {
            if (!$_GET['check']) {
                showmessage(lang('plugin/jameson_read', 'bixuxuanzepiaoju'));
            }
            $my = C::t('#jameson_read#jamesonread_authors')->fetch($_G['uid']);
            foreach ($_GET['check'] as $key => $value) {
                $type  = intval($_GET['type'][$key]);
                $field = trim($_GET['field'][$key]);
                $info  = DB::fetch_first('SELECT * FROM %t WHERE type=%d', array('jamesonread_topics', $type));
                $nums  = (int) $my[$field];
                C::t('#jameson_read#jamesonread_topics')->insert(array(
                    'name'    => $info['name'],
                    'descro'  => $_G['member']['username'],
                    'book_1'  => $nums,
                    'book_2'  => $nums * ($info['adv']),
                    'addtime' => TIMESTAMP,
                    'type'    => 201,
                    'image'   => daddslashes($_GET['zhanghuinfo']),
                    'url'     => $_G['uid'],
                    'adv'     => $type,
                    'book_3'  => $info['adv'],
                ));

            }
            showmessage(lang('plugin/jameson_read', 'caozuochenggong'), './plugin.php?id=jameson_read&contrl=author&act=shupiao');
        }
    }
    public function edit()
    {
        global $_G;
        $books      = C::t('#jameson_read#jamesonread_books')->fetchAllInfoById($_GET['book_id']);
        $authorinfo = C::t('#jameson_read#jamesonread_authors')->fetch($_G['uid']);
        if ($_GET['tid']) {
            if (!$authorinfo['allowedit']) {
                showmessage(lang('plugin/jameson_read', 'buyunxubianjizhangjie'), dreferer(), 'error');
            }
            $columinfo = C::t('#jameson_read#jamesonread_colums')->fetch_bytid($_GET['tid']);
            $message   = C::t('forum_post')->fetch('tid:' . $_GET['tid'], $_GET['pid']);
            if (preg_match("/jameson_read\s*$/ism", $message['message'])) {
                include_once './source/function/function_discuzcode.php';
                $_G['forum_attachpids'][] = $columinfo['pid'];
                if (preg_match_all("/\[attach\](\d+)\[\/attach\]/i", $message['message'], $matchaids)) {
                    $_G['forum_attachtags'][$columinfo['pid']] = $matchaids[1];
                }
                $tupianfujian = array();
                $_G['tid']    = $columinfo['tid'];
                require_once libfile('function/attachment');
                parseattach($_G['forum_attachpids'], $_G['forum_attachtags'], $tupianfujian);
                if ($tupianfujian[$columinfo['pid']]['attachments']) {
                    foreach ($tupianfujian[$columinfo['pid']]['attachments'] as $key => $value) {
                        if (in_array(strtolower($value['ext']), array('jpg', 'png', 'gif'))) {
                            $img = '<img  src="'
                                . $value['url']
                                . $value['attachment']
                                . '" />';
                            $patt = "/\[attach\]("
                                . $key
                                . ")\[\/attach\]/i";
                            $message['message'] = preg_replace($patt, $img, $message['message']);
                        }
                    }
                }
                $message['message'] = preg_replace(array("/\[audio\](.*?)\[\/audio\]/", "|\[img=?(\d+)?,?(\d+)?\](.*?)\[/img\]|"), array('<audio src="$1"  controls></audio>', '<img src="$3" width="$1" height="$2">'), $message['message']);
                // 原始解析后
                $codemessage = trim(discuzcode(
                    $message['message'],0, 0, 1,1, 1, 1, 1, 0, '0', $columinfo['uid'],'0')
                );

                $message = preg_replace(array(
                    "/[^=_\/]jameson_read/ism",
                    "/\[code\][^\[]*\[\/code\]/ism",
                    "/\[quote\]/",
                    "/\[\/quote\]/"
                ),
                    array(
                        '',
                        '######',
                        '<blockquote>',
                        '</blockquote>',
                    ), $codemessage);

                preg_match_all('/\[code\]([^\[]*)\[\/code\]/is', $codemessage, $codehtml);
                // 存在源代码格式
                if ($codehtml) {
                    $codearray = array();
                    foreach ($codehtml[1] as $key => $value) {
                        $tmp = '<pre>'
                        . dhtmlspecialchars($value)
                            . '</pre>';
                        $message = preg_replace('/######/', $tmp, $message);
                    }
                }
                $message = stripcslashes($message);
            } else {
                $aftermessage = preg_replace(
                    array(
                    "/<code>(.*?)<\/code>/is",
                     ),
                    array(
                        '######',
                    ), $message['message']);
                preg_match_all('/<code>(.*?)<\/code>/is', $message['message'], $codehtml2);
                // 存在源代码格式
                if ($codehtml2) {
                    $codearray = array();
                    foreach ($codehtml2[1] as $key => $value) {
                        $tmp = '<code>'
                        . preg_replace(array('/</','/>/'),array('&lt;','&gt;'),$value)
                            . '</code>';
                        $aftermessage = preg_replace('/######/', $tmp, $aftermessage,1);
                    }
                }
                $message = stripcslashes($aftermessage);
            }
            if (!preg_match("/<br\s*\/?>/i", $message)) {
                $message = nl2br($message);
            }
        }

        $navtitle = ($columinfo ? $columinfo['subject'] : lang('plugin/jameson_read', 'tianjiaxinzhangjie')) . '-' . lang('plugin/jameson_read', 'zuozhezhongxin');
        include template("jameson_read:author_edit");
    }
    public function postzhangjie()
    {
        global $_G;
        if ($_GET['formhash'] != FORMHASH) {
            showmessage(lang('plugin/jameson_read', 'laiyuanfeifa'));
        }
        $book_id = intval($_GET['book_id']);
        if (!$book_id) {
            // 如果被禁止发布图书
            showmessage(lang('plugin/jameson_read', 'wuquanfabu'), dreferer());
        }
        $authorinfo = C::t('#jameson_read#jamesonread_authors')->fetch($_G['uid']);
        $books      = C::t('#jameson_read#jamesonread_books')->fetchAllInfoById($book_id);
        $data       = array(
            "subject" => daddslashes($_GET['subject']),
            "length"  => intval($_GET['zishu']),
            "j_id"    => intval($_GET['j_id']),
        );
        if ($authorinfo[$authorinfo['setsj']]) {
            $data['price'] = intval($_GET['price']);
            if ($authorinfo['setsj'] == 'zgsj' && $data['price'] > $authorinfo['zgsj']) {
                $data['price'] = $authorinfo['zgsj'];
            }
        }

        $message = daddslashes($_GET['editorValue']);
        if ($_GET['tid']) {
            $tid = intval($_GET['tid']);
            $pid = intval($_GET['pid']);
            $old = C::t('#jameson_read#jamesonread_colums')->fetch_bytid($tid);
            DB::update('jamesonread_colums', $data, DB::field('tid', $tid));
            C::t('forum_post')->update('tid:' . $tid, $pid, array('message' => $message));
            C::t('forum_thread')->update($tid, array('subject' => $data['subject']));
            DB::update('jamesonread_books', array(
                'hascol' => $books['hascol'] + 1,
                'zishu'  => $books['zishu'] + $data['length'] - $old['length'],
            ), DB::field('book_id', $book_id));
        } else {
            $lastzj = (int) DB::result_first('SELECT zhangjie FROM %t WHERE book_id=%d ORDER BY zhangjie DESC', array('jamesonread_colums', $book_id));
            // 首先插入  thread
            $tid = C::t("forum_thread")->insert(array(
                'fid'        => intval($_G['jameson_read']['fid']),
                'author'     => $_G['member']['username'],
                'authorid'   => $_G['uid'],
                'subject'    => $data['subject'],
                'dateline'   => TIMESTAMP,
                'lastpost'   => TIMESTAMP,
                'lastposter' => $_G['member']['username'],
            ), true);
            // 再插入post表
            $pid = C::t('forum_post_tableid')->insert(array('pid' => ''), true);
            C::t('forum_post')->insert('tid:' . $tid, array(
                'tid'       => $tid,
                'pid'       => $pid,
                'fid'       => intval($_G['jameson_read']['fid']),
                'first'     => 1,
                'author'    => $_G['member']['username'],
                'authorid'  => $_G['uid'],
                'subject'   => $data['subject'],
                'message'   => $message,
                'dateline'  => TIMESTAMP,
                'useip'     => $_G['clientip'],
                'port'      => $_SERVER['REMOTE_PORT'],
                'bbcodeoff' => 0,
                'smileyoff' => 0,
                'htmlon'    => 1,
                'position'  => 1,
            ), true);
            C::t('#jameson_read#jamesonread_colums')->insert(array(
                'book_id'     => $book_id,
                'category_id' => $books['category_id'],
                'uid'         => $_G['uid'],
                'fid'         => intval($_G['jameson_read']['fid']),
                'price'       => $data['price'] ? $data['price'] : 0,
                'tid'         => $tid,
                'pid'         => $pid,
                'zhangjie'    => ++$lastzj,
                'addtime'     => TIMESTAMP,
                'j_id'        => $data['j_id'],
                'subject'     => $data['subject'],
                'length'      => $data['length'],
            ));
            DB::update('jamesonread_books', array(
                'hascol' => $books['hascol'] + 1,
                'zishu'  => $books['zishu'] + $data['length'],
            ), DB::field('book_id', $book_id));
            C::t('#jameson_read#jamesonread_update')->add(array(
                'book_id'=>$book_id,
                'tid'=>$tid,
                'pid'=>$pid,
                'category_id'=>$books['category_id'],
                'book_name'=>$books['book_name'],
                'subject'=>$data['subject'],
                'author'=>$books['author'],
                'addtime'=>TIMESTAMP,
                'parent_id'=>$books['parent_id'],
                'image'=>$books['image']
            ));
            DB::query('UPDATE ' . DB::table('forum_forum') . ' SET ' . DB::field('todayposts', '1', '+') . ' WHERE ' . DB::field('fid', $_G['jameson_read']['fid']));
            // 如果发表文章奖励积分
            if ($_G['jameson_read']['ftjltrameid'] && $_G['jameson_read']['ftjljine']) {
                updatemembercount($_G['uid'],
                array($_G['jameson_read']['ftjltrameid'] => $_G['jameson_read']['ftjljine']),
                true, 'FTJ', $tid, lang('plugin/jameson_read', 'fatiejiangli'));
            }
        }
        
        C::t('#jameson_read#jamesonread_books')->clear_cache(array("bookinfo-".$book_id."-".$_G['uid'], "bookinfo-".$book_id."-0"));
        C::t('#jameson_read#jamesonread_colums')->clear_cache(array("mulu".$book_id));
        dheader('location:' . trim($_G['siteurl'], '/') . '/' . jamesonurl('thread', $tid, $pid, $_G['uid']));
    }
    public function postbook()
    {
        global $_G;
        if ($_GET['formhash'] != FORMHASH) {
            showmessage(lang('plugin/jameson_read', 'laiyuanfeifa'));
        }
        $authorinfo = C::t('#jameson_read#jamesonread_authors')->fetch($_G['uid']);
        if (!$_GET['book_id'] && !$authorinfo['status']) {
            // 如果被禁止发布图书
            showmessage(lang('plugin/jameson_read', 'wuquanfabu'), dreferer());
        }
        if (!trim($_GET['book_name'])) {
            showmessage(lang('plugin/jameson_read', 'bixutianxieshuming'));
        }
        $data           = array();
        $data['author'] = daddslashes(dhtmlspecialchars(trim($_GET['author'])));
        $book_id        = intval($_GET['book_id']);
        $forward        = daddslashes(trim($_GET['forward']));
        $caozuotype     = '';
        if (!$book_id) {
            $data['uid']     = intval($_G['uid']);
            $data['dpcount'] = $data['scores'] = 0;
            $caozuotype      = 'add';
        } else {
            $caozuotype = 'edit';
        }
        // debug($caozuotype);
        $data['addtime']     = TIMESTAMP;
        $data['book_name']   = daddslashes(dhtmlspecialchars(trim($_GET['book_name'])));
        $data['desco']       = daddslashes(dhtmlspecialchars($_GET['book_descro']));
        $data['authorinfo']  = daddslashes(dhtmlspecialchars($_GET['authorinfo']));
        $data['shuxing']     = daddslashes(dhtmlspecialchars($_GET['shuxing']));
        $data['fletter']     = daddslashes(dhtmlspecialchars(trim($_GET['fletter'])));
        $data['plan']        = intval($_GET['plan']);
        $data['category_id'] = intval($_GET['category_id']);
        $data['parent_id']   = intval($_GET['parent_id']);
        // debug($_GET);
        if ($_GET['is_pdf'] && isset($_GET['bookmoney'])) {
            $data['bookmoney'] = ($authorinfo['setsj'] == 'zgsj' && ($authorinfo['zgsj'] < $_GET['bookmoney'])) ? $authorinfo['zgsj'] : intval($_GET['bookmoney']);
        }

        $res = false;
        if (!$book_id && isset($_FILES['imgname'])) {
            $upload = new discuz_upload();
            $upload->init($_FILES['imgname'], 'forum');
            if ($upload->is_image_ext($upload->fileext($_FILES['imgname']['name']))) {
                if ($upload->save()) {
                    $data['image'] = $upload->attach['attachment'];
                } else {
                    $message = '#' . lang('plugin/jameson_read', 'shangchuanfengmianshibai');
                }
            } else {
                $message = '#' . lang('plugin/jameson_read', 'shangchuanfengmianshibai');
            }
            unset($upload);
        }else if(!$book_id){
            $data['image'] = trim($_GET['imgname']);
        }
        if ($book_id) {
            $res = C::t('#jameson_read#jamesonread_books')->update($book_id, $data);
            C::t("#jameson_read#jamesonread_books")->clear_cache(array($book_id . '_0', $book_id . '_' . $_G['uid']));
        } else {
            $data['author'] = $data['author'] ? $data['author'] : $_G['username'];
            $data['is_pdf'] = intval($_GET['is_pdf']);
            $res            = C::t('#jameson_read#jamesonread_books')->insert($data, true);
            if ($res) {
                $book_id = $res;
                if (!DB::result_first('SELECT count(*) FROM %t WHERE author_id=%d', array('jamesonread_authors', $_G['uid']))) {
                    C::t('#jameson_read#jamesonread_authors')->insert(array(
                        'author_id'   => $_G['uid'],
                        'status'      => 1,
                        'edit'        => 1,
                        'allowedit'   => 1,
                        'tuijianpiao' => 0,
                        'cuigengpiao' => 0,
                        'yuepiao'     => 0,
                        'zgsj'        => 0,
                        'qzsj'        => 0,
                        'setsj'       => 'zgsj',
                    ));
                }
            } else {
                showmessage(lang('plugin/jameson_read', 'caozuoshibai') . $fileflag, dreferer());
            }
        }
        // 判断是否存在上传的txt文件
        $fileflag = '';
        if ($res && $_FILES['upload_txt']['name']) {
            if ($_FILES['upload_txt']['error'] || ($_FILES['upload_txt']['type'] != 'text/plain') || (stripos($_FILES['upload_txt']['name'], '.txt') === false)) {
                $fileflag = '#' . $this->error($_FILES['upload_txt']['error']);
            } else {
                $this->uploadtxt($_FILES['upload_txt']['tmp_name'],C::t('#jameson_read#jamesonread_books')->fetch($book_id));
                $fileflag = '#' . lang('plugin/jameson_read', 'shangchuanwancheng');
            }
        }
        // 创建默认分卷
        if (!$_FILES['upload_txt']['name'] && ($caozuotype == 'add') && $book_id) {
            C::t('#jameson_read#jamesonread_fenjuan')->insert(array(
                'order_num' => 1,
                'j_title'   => lang('plugin/jameson_read', 'weifenjuan'),
                'book_id'   => $book_id,
            ));
        }
        C::t('#jameson_read#jamesonread_books')->clear_cache(array("bookinfo-".$book_id."-".$_G['uid'], "bookinfo-".$book_id."-0"));
        C::t('#jameson_read#jamesonread_colums')->clear_cache(array("mulu".$book_id));
        if (!$res) {
            showmessage(lang('plugin/jameson_read', 'caozuoshibai') . $fileflag, dreferer());
        } else {
            if($_GET['is_pdf'] && $caozuotype=='add'){
               $forward = 'book_pdf';
            }
            showmessage(lang('plugin/jameson_read', 'caozuochenggong') . $fileflag, './plugin.php?id=jameson_read&contrl=author&act=book&book_id=' . $book_id . '&forward=' . $forward);
        }
    }
    // 上传pdf文件
    public function postpdf()
    {
        global $_G;
        if (($_GET['formhash'] != FORMHASH) || !$_GET['book_id']) {
            showmessage(lang('plugin/jameson_read', 'laiyuanfeifa'));
        }
        // 如果是更新
        if ($_GET['pdfname'] && is_array($_GET['pdfname'])) {
            foreach ($_GET['pdfname'] as $key => $value) {
                $data             = array();
                $data['name']     = daddslashes(dhtmlspecialchars(trim($value)));
                $data['ordernum'] = intval($_GET['pdfordernum'][$key]);
                $data['book_id']  = $book_id  = $_GET['book_id'];
                $data['addtime']  = TIMESTAMP;
                C::t('#jameson_read#jamesonread_pdf')->update($key, $data);
            }
        }
        if ($_FILES['newpdffile']['error'] && ($_FILES['newpdffile']['error'] != 4)) {
            showmessage($this->geterror($_FILES['newpdffile']['error']), '');
        }
        // 如果是新增
        if ($_GET['newpdfurl'] || isset($_FILES['newpdffile'])) {
            $data = array();
            // 初次判断 判断类型是否pdf，通过FILES中的type和文件后缀
            if (!$_GET['newpdfurl'] && isset($_FILES['newpdffile'])) {
                if (!in_array(strtolower($_FILES['newpdffile']['type']), array('application/pdf', 'application/octet-stream', '"application/octet-stream')) || (fileext($_FILES['newpdffile']['name']) != 'pdf')) {
                    showmessage(lang('plugin/jameson_read', 'shangchuanleixingcuowu'), '');
                }
            }
            $data['name']     = trim($_GET['newpdfname']) ? daddslashes(dhtmlspecialchars(trim($_GET['newpdfname']))) : 'unknow.pdf';
            $data['book_id']  = $book_id  = $_GET['book_id'];
            $data['addtime']  = TIMESTAMP;
            $data['ordernum'] = 1 + intval(DB::result_first('SELECT ordernum FROM  %t WHERE book_id=%d ORDER BY ordernum DESC LIMIT %d', array('jamesonread_pdf', $_GET['book_id'], 1)));
            if (trim($_GET['newpdfurl'])) {
                $data['url'] = daddslashes(dhtmlspecialchars(trim($_GET['newpdfurl'])));
            } else {
                if (isset($_FILES['newpdffile']) && !$_FILES['newpdffile']['error']) {
                    $upload = new discuz_upload();
                    $upload->init($_FILES['newpdffile'], 'forum');
                    // 二次判断
                    if (!in_array($upload->attach['type'], array('application/pdf', 'application/octet-stream', '"application/octet-stream')) || ($upload->attach['ext'] != 'pdf')) {
                        showmessage(lang('plugin/jameson_read', 'shangchuanleixingcuowu'), '');
                    }
                    $newpdfname               = substr($upload->attach['attachment'], 0, strrpos($upload->attach['attachment'], '.attach')) . '.pdf';
                    $upload->attach['target'] = DISCUZ_ROOT . './data/attachment/jamesonpdf/' . $newpdfname;
                    @dmkdir(DISCUZ_ROOT . '/data/attachment/jamesonpdf/' . $upload->attach['attachdir']);
                    if ($upload->save()) {
                        $data['url'] = './data/attachment/jamesonpdf/' . $newpdfname;
                    } else {
                        showmessage(lang('plugin/jameson_read', 'shangchuanpdfshibai'));
                    }
                }
            }
            C::t('#jameson_read#jamesonread_pdf')->insert($data);
        }
        C::t('#jameson_read#jamesonread_books')->clear_cache(array("bookinfo-".$book_id."-".$_G['uid'], "bookinfo-".$book_id."-0"));
        C::t('#jameson_read#jamesonread_colums')->clear_cache(array("mulu".$book_id));
        showmessage(lang('plugin/jameson_read', 'caozuochenggong'), './plugin.php?id=jameson_read&contrl=author&act=book&book_id=' . $_GET['book_id'] . '&forward=book_pdf');
    }
    public function geterror($error)
    {
        switch ($error) {
            case 1:
                return lang('plugin/jameson_read', 'daxiaochaoguophpxianzhi') . '<strong>' . ini_get('upload_max_filesize') . '</strong>';
                // 文件大小超出了服务器的空间大小
                break;
            case 2:
                return lang('plugin/jameson_read', 'taidaliulanqi');
                break;
            case 3:
                // 文件仅部分被上传
                return lang('plugin/jameson_read', 'shangchuanbuwanzheng');
                break;
            case 4:
                // 没有找到要上传的文件
                return lang('plugin/jameson_read', 'meiyouxuanzeshangchuanwenjian');
                break;
            case 5:
            // 服务器临时文件夹丢失
            case 6:
                // 文件写入到临时文件夹出错
                return lang('plugin/jameson_read', 'shangchuanchucuo');
                break;
        }
    }
    public function postfenjuan()
    {
        global $_G;
        if ($_GET['formhash'] != FORMHASH) {
            showmessage(lang('plugin/jameson_read', 'laiyuanfeifa'));
        }
        $data            = array();
        $data['j_title'] = daddslashes(dhtmlspecialchars($_GET['newjuanname']));
        if (!$data['j_title']) {
            showmessage(lang('plugin/jameson_read', 'juanmingcuowu'), dreferer(), 'error');
        }
        $book_id     = intval($_GET['book_id']);
        $oldordernum = (int) DB::result_first('SELECT order_num FROM %t WHERE book_id=%d ORDER BY order_num DESC', array('jamesonread_fenjuan', $book_id));
        $oldordernum++;
        $data['book_id']   = $book_id;
        $data['order_num'] = $oldordernum;
        C::t('#jameson_read#jamesonread_fenjuan')->insert($data);
        C::t('#jameson_read#jamesonread_fenjuan')->clear_cache(array('by' . $book_id, 'all' . $book_id));
        C::t('#jameson_read#jamesonread_books')->clear_cache(array("bookinfo-".$book_id."-".$_G['uid'], "bookinfo-".$book_id."-0"));
        C::t('#jameson_read#jamesonread_colums')->clear_cache(array("mulu".$book_id));
        showmessage(lang('plugin/jameson_read', 'gengxinchenggong'), './plugin.php?id=jameson_read&contrl=author&act=book&book_id=' . $book_id . '&forward=' . $_GET['forward']);
    }
    public function postbookindex()
    {
        global $_G;
        if (FORMHASH != trim($_GET['formhash'])) {
            showmessage(lang('plugin/jameson_read', 'laiyuanfeifa'), dreferer());
        }
        if ($_GET['remove']) {
            $authorinfo = C::t('#jameson_read#jamesonread_authors')->fetch($_G['uid']);
            if (!$authorinfo['edit']) {
                showmessage(lang('plugin/jameson_read', 'wuquanbianji'), dreferer());
            }
            foreach ($_GET['remove'] as $id => $value) {
                jamesonread_deletebook($id);
            }
        }
        foreach ($_GET['bookname'] as $key => $value) {
            if (trim($value)) {
                $data              = array();
                $data['book_name'] = daddslashes(dhtmlspecialchars($value));
                $data['ordernum']  = intval($_GET['ordernum'][$key]);
                C::t('#jameson_read#jamesonread_books')->update($key, $data);
                C::t('#jameson_read#jamesonread_books')->clear_cache(array("bookinfo-".$key."-".$_G['uid'], "bookinfo-".$key."-0"));
            }
        }
        showmessage(lang('plugin/jameson_read', 'gengxinchenggong'), dreferer());
    }
    public function uploadtxt($tmpname, $bookinfo=array())
    {
        global $_G;
        $book_id = $bookinfo['book_id'];
        $txt = trim(file_get_contents($tmpname));
        if (xfxs_isutf($txt)) {
            if (strtolower(CHARSET) != 'utf-8') {
                $txt = diconv($txt, 'utf-8', CHARSET);
            }
        } else {
            if (strtolower(CHARSET) == 'utf-8') {
                $txt = diconv($txt, 'gbk', 'utf-8');
            }
        }
        $data = explode('###', $txt);
        unset($data[0]);
        // 插入分卷
        // 当前已有多少个分卷
        $thisfenjuan = DB::fetch_first('SELECT * FROM %t WHERE book_id=%d ORDER BY order_num DESC LIMIT 1', array('jamesonread_fenjuan', $book_id));
        $zhangjieid  = (int) DB::result_first('SELECT zhangjie FROM %t WHERE book_id=%d ORDER BY zhangjie DESC ', array('jamesonread_colums', $book_id));
        if (!$thisfenjuan) {
            $jid = C::t('#jameson_read#jamesonread_fenjuan')->insert(array(
                'j_title'   => lang('plugin/jameson_read', 'fenjuanlang') . '1',
                'order_num' => 1,
                'book_id'   => $book_id,
            ), true);
        } else {
            $jid = $thisfenjuan['j_id'];
        }
        $changdu = 0;
        foreach ($data as $key => $value) {
            $value = trim($value);
            if (!$value) {
                continue;
            }
            $zhangjieid++;
            $tmpos      = stripos($value, "\n");
            $tmpsubject = trim(substr($value, 0, $tmpos));
            
            $tmpmessage = trim(substr($value, $tmpos + 1));
            if (!$tmpsubject || !$tmpmessage) {
                continue;
            }
            $changdu += xfxs_cnleng($tmpmessage,CHARSET);
            if(!preg_match('/<(br|p)[^>]*?>/ism', $tmpmessage)){
            	$tmpmessage = nl2br($tmpmessage);
            }
            // 首先插入  thread
            $tid = C::t("forum_thread")->insert(array(
                'fid'        => intval($_G['jameson_read']['fid']),
                'author'     => $_G['username'],
                'authorid'   => $_G['uid'],
                'subject'    => $tmpsubject,
                'dateline'   => TIMESTAMP,
                'lastpost'   => TIMESTAMP,
                'lastposter' => $_G['username'],
                'special'    => 127,
                'status'     => 544,
            ), true);
            // 再插入post表
            $pid = C::t('forum_post_tableid')->insert(array('pid' => ''), true);
            C::t('forum_post')->insert('tid:'.$tid, array(
                'tid'       => $tid,
                'pid'       => $pid,
                'fid'       => intval($_G['jameson_read']['fid']),
                'first'     => 1,
                'author'    => $_G['username'],
                'authorid'  => $_G['uid'],
                'subject'   => $tmpsubject,
                'message'   => $tmpmessage,
                'dateline'  => TIMESTAMP,
                'useip'     => $_G['clientip'],
                'port'      => $_SERVER['REMOTE_PORT'],
                'bbcodeoff' => 0,
                'smileyoff' => 0,
                'htmlon'    => 1,
                'position'  => 1,
            ), true);
            C::t('#jameson_read#jamesonread_colums')->insert(array(
                'book_id'     => $book_id,
                'category_id' => $bookinfo['category_id'],
                'uid'         => $_G['uid'],
                'fid'         => intval($_G['jameson_read']['fid']),
                'tid'         => $tid,
                'pid'         => $pid,
                'zhangjie'    => $zhangjieid,
                'addtime'     => TIMESTAMP,
                'j_id'        => $jid,
                'subject'     => $tmpsubject,
                'length'      => xfxs_cnleng($tmpmessage,CHARSET),
            ));
                C::t('#jameson_read#jamesonread_update')->add(array(
                    'book_id'=>$book_id,
                    'tid'=>$tid,
                    'pid'=>$pid,
                    'category_id'=>$bookinfo['category_id'],
                    'book_name'=>$bookinfo['book_name'],
                    'subject'=>$tmpsubject,
                    'author'=>$bookinfo['author'],
                    'addtime'=>TIMESTAMP,
                    'parent_id'=>$bookinfo['parent_id'],
                    'image'=>$bookinfo['image']?$bookinfo['image']:''
                ));
        }
        DB::update('jamesonread_books', array(
            'zishu'  => intval($bookinfo['zishu']) + $changdu,
            'hascol' => count($data) + intval($bookinfo['hascol']),
        ), DB::field('book_id', $book_id));
        C::t('#jameson_read#jamesonread_books')->clear_cache(array("bookinfo-".$book_id."-".$_G['uid'], "bookinfo-".$book_id."-0"));
        C::t('#jameson_read#jamesonread_colums')->clear_cache(array("mulu".$book_id));
        return true;
    }
    public function error($code)
    {
        switch ($code) {
            case 1:
                return lang('plugin/jameson_read', 'daxiaochaoguophpxianzhi');
                break;
            case 2:
                return lang('plugin/jameson_read', 'daxiaochaoguohtmlxianzhi');
                break;
            case 3:
                return lang('plugin/jameson_read', 'shangchuanbuwanzheng');
                break;
            case 4:
                return lang('plugin/jameson_read', 'meiyouxuanzeshangchuanwenjian');
                break;
            default:
                return lang('plugin/jameson_read', 'shangchuanchucuo');
                break;
        }
    }
}
